# 发帖、取帖、取用户相关帖子、搜索帖子

import json
from django.http import JsonResponse
from web.models import *

from django import forms
from django.forms.models import model_to_dict
from web.apis.module import Module

from django.core.paginator import Paginator

from web import utils


tools = utils.Utils()

module = Module()

# 创建分类
class CreateCategoryForm(forms.ModelForm):
    class Meta:
        model = PostCategory
        fields = ['name']


def create_category(request):
    if request.method == 'POST':
        form = CreateCategoryForm(request.POST)
        if form.is_valid():
            form.save()
            data = model_to_dict(form.instance)
            return JsonResponse(tools.Response(code=200, message='创建成功', data=data))
        else:
            error = tools.Forms_GetError(form)
            return JsonResponse(tools.Response(code=400, message=error[1], data=error[0]))


# 获取分类
def get_category(request):
    category = PostCategory.objects.all()
    data = [model_to_dict(i) for i in category]
    return JsonResponse(tools.Response(code=200, message='获取成功', data=data))


# 帖子
class CreatePostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'content', 'user_id', 'category', 'cover']




# 创建帖子
def create_post(request):
    if request.method == 'POST':
        form = CreatePostForm(request.POST, files=request.FILES)
        if form.is_valid():
            form.save()
            data = module.post_data_format(form.instance)

            return JsonResponse(tools.Response(code=200, message='创建成功', data=data))
        else:
            error = tools.Forms_GetError(form)
            return JsonResponse(tools.Response(code=400, message=error[1], data=error[0]))


# 编辑帖子
def edit_post(request):
    post_id = request.POST.get('post_id')
    user_id = request.POST.get('user_id')
    post = Post.objects.filter(id=post_id, user_id=user_id).first()
    if not post:
        return JsonResponse(tools.Response(code=400, message='帖子不存在'))
    
    form = CreatePostForm(request.POST, instance=post, files=request.FILES)
    if form.is_valid():
        form.save()
        data = module.post_data_format(form.instance)
        return JsonResponse(tools.Response(code=200, message='编辑成功', data=data))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=error[1], data=error[0]))


# 获取作者下的全部帖子
def get_author_post(request):
    user_id = request.GET.get('user_id')
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    # 获取作者下的全部帖子
    post = Post.objects.filter(user_id=user_id).order_by("-created_at")
    # 分页
    paginator = Paginator(post, page_size)
    page_data = paginator.page(page)
    data = []
    for i in page_data.object_list:
        new_item = module.post_data_format(i, level=1)
        # 作者
        new_item['user'] = {
            'username': i.user_id.username,
            'avatar': i.user_id.avatar.url
        }
        data.append(new_item)
    result = {
        'data': data,
        'total': paginator.count,
        'page': page,
        'page_size': page_size
    }
    return JsonResponse(tools.Response(code=200, message='获取成功', data=result))


# 根据分类id获取帖子
def get_category_post(request):
    category_id = request.GET.get('category_id')
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    post = Post.objects.filter(category_id=category_id).order_by("-created_at")
    paginator = Paginator(post, page_size)
    page_data = paginator.page(page)
    data = []
    for i in page_data.object_list:
        new_item = module.post_data_format(i, level=1)
        # 作者
        new_item['user'] = {
            'username': i.user_id.username,
            'avatar': i.user_id.avatar.url
        }
        data.append(new_item)
    return JsonResponse(tools.Response(code=200, message='获取成功', data=data))


# 搜索帖子
def search_post(request):
    keyword = request.GET.get('keyword')
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    post = Post.objects.filter(title__icontains=keyword)
    paginator = Paginator(post, page_size)
    page_data = paginator.page(page)
    data = []
    for i in page_data.object_list:
        new_item = module.post_data_format(i, level=1)
        # 作者
        new_item['user'] = {
            'username': i.user_id.username,
            'avatar': i.user_id.avatar.url
        }
        data.append(new_item)
    
    return JsonResponse(tools.Response(code=200, message='获取成功', data=data))


# 获取帖子详情
def get_post_detail(request):
    try:
        # 需要携带用户id
        user_id = request.GET.get('user_id')
        user = Users.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse(tools.Response(code=400, message='需要携带观看用户id'))
        
        post_id = request.GET.get('post_id')
        post = Post.objects.filter(id=post_id).first()
        if not post:
            return JsonResponse(tools.Response(code=400, message='帖子不存在'))
        data = module.post_data_format(post, level=0, fields=1)
        return JsonResponse(tools.Response(code=200, message='获取成功', data=data))
    except Exception as e:
        return JsonResponse(tools.Response(code=400, message=str(e)))


# 点赞帖子
def like_post(request):
    # 需要携带用户id
    user_id = request.GET.get('user_id')
    user = Users.objects.filter(user_id=user_id).first()
    if not user:
        return JsonResponse(tools.Response(code=400, message='需要携带点赞用户id'))
    
    post_id = request.GET.get('post_id')
    post = Post.objects.filter(id=post_id).first()
    if not post:
        return JsonResponse(tools.Response(code=400, message='帖子不存在'))
    
    # 判断用户是否已经点赞
    post_like = PostLike.objects.filter(user_id=user_id, post_id=post_id).first()
    if not post_like:
        post_like = PostLike.objects.create(user_id=user, post_id=post, is_like=True)
        post_like.save()
        post.likes += 1
        post.save()
    else:
        if post_like.is_like:
            return JsonResponse(tools.Response(code=400, message='您已经点过赞过了'))
        post_like.is_like = True
        post_like.save()
        post.likes += 1
        post.save()

    return JsonResponse(tools.Response(code=200, message='点赞完成'))


# 取消点赞
def cancel_like_post(request):
    user_id = request.GET.get('user_id')
    post_id = request.GET.get('post_id')
    user = Users.objects.filter(user_id=user_id).first()
    if not user:
        return JsonResponse(tools.Response(code=400, message='需要携带点赞用户id'))
    
    post_like = PostLike.objects.filter(user_id=user_id, post_id=post_id).first()
    if not post_like or not post_like.is_like:
        return JsonResponse(tools.Response(code=400, message='您还没有点过赞'))
        
    
    post = Post.objects.filter(id=post_id).first()
    if not post:
        return JsonResponse(tools.Response(code=400, message='帖子不存在'))
    
    post_like.is_like = False
    post_like.save()
    post.likes -= 1
    post.save()
    
    return JsonResponse(tools.Response(code=200, message='取消点赞完成'))


# 设置帖子是否置顶和取消置顶
def set_post_pinned(request):
    user_id = request.GET.get('user_id')
    post_id = request.GET.get('post_id')
    is_pinned = request.GET.get('is_pinned')
    is_pinned = True if is_pinned == 'true' else False
    user = Users.objects.filter(user_id=user_id).first()
    if not user:
        return JsonResponse(tools.Response(code=400, message='需要携带用户id'))
    
    post = Post.objects.filter(id=post_id, user_id=user_id).first()
    if not post:
        return JsonResponse(tools.Response(code=400, message='帖子不存在'))
    
    # 判断用户是否为超级管理员
    super_admin = SuperAdmin.objects.filter(user_id=user_id).first()
    if not super_admin:
        return JsonResponse(tools.Response(code=400, message='您不是超级管理员'))
    
    # 设置帖子置顶
    post.is_pinned = is_pinned
    post.save()
    
    return JsonResponse(tools.Response(code=200, message='设置成功'))
    

class CreatePostMediaForm(forms.ModelForm):
    class Meta:
        model = PostMedia
        fields = ['post_id', 'media_url', 'media_type', 'order']


# 创建帖子媒体资源
def create_post_media(request):
    if request.method == 'POST':
        form = CreatePostMediaForm(request.POST, files=request.FILES)
        if form.is_valid():
            post_id = request.POST.get('post_id')
            order = request.POST.get('order')
            if order:
                order = int(order)
                post = Post.objects.filter(id=post_id).first()
                if not post:
                    return JsonResponse(tools.Response(code=400, message='帖子不存在'))
                # 获取帖子下的媒体资源数量
                media_count = PostMedia.objects.filter(post_id=post_id).count()
                # 新增的媒体资源顺序不能小于等于媒体资源数量
                if order <= media_count:
                    return JsonResponse(tools.Response(code=400, message='新增的媒体资源顺序不能小于等于媒体资源数量'))
            form.save()
            data = model_to_dict(form.instance)
            data['media_url'] = form.instance.media_url.url
            data['media_type'] = form.instance.get_media_type_display()
            return JsonResponse(tools.Response(code=200, message='创建成功', data=data))
        else:
            error = tools.Forms_GetError(form)
            return JsonResponse(tools.Response(code=400, message=error[1], data=error[0]))

# 获取帖子媒体资源
def get_post_media(request):
    try:
        post_id = request.GET.get('post_id')
        if not post_id:
            return JsonResponse(tools.Response(code=400, message='需要携带帖子id'))
        post_media = PostMedia.objects.filter(post_id=post_id)
        data = []
        for item in post_media:
            new_item = model_to_dict(item)
            new_item['media_url'] = item.media_url.url
            new_item['media_type'] = item.get_media_type_display()
            data.append(new_item)
        return JsonResponse(tools.Response(code=200, message='获取成功', data=data))
    except Exception as e:
        return JsonResponse(tools.Response(code=400, message=str(e)))


# 创建帖子评论
class CreatePostCommentForm(forms.ModelForm):
    class Meta:
        model = PostComment
        fields = ['post_id', 'user_id', 'content']


# 创建帖子评论
def create_post_comment(request):
    if request.method == 'POST':
        try:
            form = CreatePostCommentForm(request.POST)
            if form.is_valid():
                form.save()
                data = model_to_dict(form.instance)
                data['create_time'] = tools.time_format(form.instance.create_time)
                data['update_time'] = tools.time_format(form.instance.update_time)
                data['user_name'] = form.instance.user_id.username
                return JsonResponse(tools.Response(code=200, message='创建成功', data=data))
            else:
                error = tools.Forms_GetError(form)
                return JsonResponse(tools.Response(code=400, message=error[1], data=error[0]))
        except Exception as e:
            return JsonResponse(tools.Response(code=400, message=str(e)))



# 获取帖子评论
def get_post_comment(request):
    try:
        post_id = request.GET.get('post_id')
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 10)
        if not post_id:
            return JsonResponse(tools.Response(code=400, message='需要携带帖子id'))
        # 获取评论
        post_comment = PostComment.objects.filter(post_id=post_id).order_by('-create_time')
        if not post_comment:
            return JsonResponse(tools.Response(code=200, message='获取成功', data=[]))
        paginator = Paginator(post_comment, page_size)
        page_data = paginator.page(page)
        data = []
        for item in page_data.object_list:
            new_item = model_to_dict(item)
            new_item['create_time'] = tools.time_format(item.create_time)
            new_item['update_time'] = tools.time_format(item.update_time)
            new_item['user'] = {
                'username': item.user_id.username,
                'avatar': item.user_id.avatar.url
            }

            data.append(new_item)
        
        result = {
            'data': data,
            'total': paginator.count,
            'page': page,
            'page_size': page_size
        }
        return JsonResponse(tools.Response(code=200, message='获取成功', data=result))
    except Exception as e:
        return JsonResponse(tools.Response(code=400, message=str(e)))











# 检查帖子是否已经点赞
def check_post_like(request):
    user_id = request.GET.get('user_id')
    post_id = request.GET.get('post_id')
    if not user_id or not post_id:
        return JsonResponse(tools.Response(code=400, message='需要携带用户id和帖子id'))
    post_like = PostLike.objects.filter(user_id=user_id, post_id=post_id).first()
    if not post_like:
        return JsonResponse(tools.Response(code=200, message='获取成功', data=False))
    return JsonResponse(tools.Response(code=200, message='获取成功', data=post_like.is_like))






# 删除帖子
def delete_post(request):
    post_id = request.GET.get('post_id')
    user_id = request.GET.get('user_id')
    user = Users.objects.filter(user_id=user_id).first()
    if not user:
        return JsonResponse(tools.Response(code=400, message='需要携带用户id'))
    post = Post.objects.filter(id=post_id, user_id=user_id).first()
    if not post:
        return JsonResponse(tools.Response(code=400, message='帖子不存在'))
    
    # 判断该帖子是不是该用户的
    if post.user_id != user:
        return JsonResponse(tools.Response(code=400, message='您没有权限删除该帖子'))
    post.delete()
    return JsonResponse(tools.Response(code=200, message='删除成功'))






# 获取帖子媒体资源顺序
def get_post_media_order(request):
    post_id = request.GET.get('post_id')
    user_id = request.GET.get('user_id')
    user = Users.objects.filter(user_id=user_id).first()
    if not user:
        return JsonResponse(tools.Response(code=400, message='需要携带用户id'))
    post = Post.objects.filter(id=post_id, user_id=user_id).first()
    if not post:
        return JsonResponse(tools.Response(code=400, message='帖子不存在'))
    
    post_media = PostMedia.objects.filter(post_id=post_id)
    if not post_media:
        return JsonResponse(tools.Response(code=400, message='帖子没有媒体资源'))
    
    post_media = post_media.order_by('order')
    data = []
    for item in post_media:
        new_item = model_to_dict(item)
        new_item['media_url'] = item.media_url.url
        new_item['media_type'] = item.get_media_type_display()
        data.append(new_item)

    return JsonResponse(tools.Response(code=200, message='获取成功', data=data))


# 编辑帖子媒体资源顺序
def edit_post_media_order(request):
    try:
        post_id = request.GET.get('post_id')
        user_id = request.GET.get('user_id')
        user = Users.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse(tools.Response(code=400, message='需要携带用户id'))
        post = Post.objects.filter(id=post_id, user_id=user_id).first()
        if not post:
            return JsonResponse(tools.Response(code=400, message='帖子不存在'))
        # 需要携带媒体资源id和顺序(客户端会上传数组字典) [[54, 2], [55, 1]]
        media_list = request.GET.get('media_list')
        media_list = json.loads(json.loads(media_list)[0])
        for item in media_list:
            media_id = item[0]
            order = item[1]
            post_media = PostMedia.objects.filter(id=media_id).first()
            post_media.order = order
            post_media.save()
        

        return JsonResponse(tools.Response(code=200, message='编辑成功'))
    except Exception as e:
        return JsonResponse(tools.Response(code=400, message=str(e)))
